<?php
$_SESSION[TINYMCE_UPLOAD] = 'upload/__install/tinymce/';

$system_id = Utils::get_param('sys', 0);
$page_id = Utils::get_param('pg', 0);


$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $system_id);
$system_name = $orm->get('pb_sys', NULL, NULL, NULL, NULL, $opts)->d[0]->name;

$opts = new stdClass();
$opts->cd = 't.id = :v1';
$opts->cdv = array(':v1' => $page_id);
$data = $orm->get('pb_page', NULL, NULL, NULL, NULL, $opts)->d;

$opts = new stdClass();
$opts->cd = 't.sys_id = :v1';
$opts->cdv = array(':v1' => $system_id);
$opts->sel = 't.id, t.parent_id, t.name, t.order';
$pages = $orm->get('pb_page', 't.order', 'ASC', NULL, NULL, $opts)->d;

$plugins = $orm->get('pb_plugin', 't.folder', 'ASC', NULL, NULL, NULL)->d;

$opts = new stdClass();
$opts->cd = 't.page_id = :v1';
$opts->cdv = array(':v1' => $page_id);
$opts->sel = 't.*, t1.folder AS __folder';
$opts->jt = 'LEFT JOIN pb_plugin AS t1 ON t1.id = t.plugin_id';
$instances = $orm->get('pb_plugin_instance', 't.name', 'ASC', NULL, NULL, $opts)->d;
?>
<style>
.pure-form * { font-size: 12px !important; font-family: FontAwesome, Trebuchet MS !important; }
.pure-form select { min-width: 150px; }
.pure-form textarea { height: 150px; width: 100%; resize: none; }
.pure_table_extra img { cursor: pointer; margin-right: 5px; }
.pure-control-group label { width: 55px !important; height: 30px; line-height: 30px; vertical-align: middle; }
.rdlnk { color: #ff0000 !important; font: bold 13px Lucida Sans Unicode !important; }
.af { float: left; border: 1px solid #aaa; margin-right: 2px; margin-bottom: 2px; cursor: pointer; padding: 5px; }
.expg { display: none; }
#toolbar {
  padding: 4px;
  display: inline-block;
  margin-bottom: 5px;
}
*+html #toolbar {
  display: inline;
}
table.form4 {
  background-color: #e9e9e9;
  border: 1px solid #666;
  color: #000;
  padding: 2px;
  padding-bottom: 20px;
  cursor: pointer;
  display: inline-block;
  margin: 2px;
  font-weight: bold;
}
</style>
<div id="toolbar" class="ui-widget-header ui-corner-all">
  <input type="checkbox" id="nav1" checked="checked" onclick="$.blockUI();location.href = __install_url + '?d=' + __dir;" /><label for="nav1">All Systems</label>
  <button class="play">play</button>
  <input type="checkbox" id="nav2" checked="checked" onclick="$.blockUI();location.href = __install_url + '?d=' + __dir + '&f=index_system' + '&sys=' + __system_id;" /><label for="nav2"><?php echo ($system_name == '') ? 'Untitled' : $system_name; ?></label>
  <button class="play">play</button>
  <input type="checkbox" id="nav3" checked="checked" onclick="$.blockUI();location.href = __install_url + '?d=' + __dir + '&f=index_system' + '&sys=' + __system_id + '&active=1';" /><label for="nav3">Pages</label>
  <button class="play">play</button>
  <input type="checkbox" id="nav4" checked="checked" disabled="disabled" /><label for="nav4" id="tb_page">&nbsp;</label>
</div>

<table cellPadding=0 cellSpacing=0 class="pure-skin-mine_tp">
  <tr>
    <td style="width: 950px; vertical-align: top;">
      
      <div class="pure-form pure-form-stacked  ui-widget-content ui-corner-all" style="padding: 10px;">
        <textarea id="html" style="height:600px;"></textarea>
        <fieldset>
          <label for="js">Javascript</label>
          <textarea id="js"></textarea>
          <label for="css">CSS</label>
          <textarea id="css"></textarea>
        </fieldset>
      </div>
      
    </td>
    <td style="width: 320px; vertical-align: top; padding-left: 10px;">
    
      <div class="pure-form pure-form-aligned ui-widget-content ui-corner-all" style="padding: 10px;">
        <legend>Basic</legend>
  
        <div class="pure-control-group">
          <label>Page</label>
          <input id="name" type="text" class="pure-input-1-2" placeholder="{New Page}"></input>
        </div>
        
        <div class="expg pure-control-group">
          <label>Icon</label>
          <button class="pure-button" onclick="select_icon(event);">Change Icon</button>
        </div>
        
        <div class="expg pure-control-group">
          <label></label>
          <label style="text-align: left; height: 65px;"><span id="icon"></span></label>
        </div>
        
        <div class="pure-control-group">
          <label>Parent</label>
          <select id="parent"></select>
        </div>
        
        <div class="pure-control-group">
          <label>Homepage</label>
          <input id="is_default" type="checkbox"></input>
        </div>
        
        <div class="pure-control-group">
          <label>On Menu</label>
          <input id="is_visible" type="checkbox">
        </div>
    
        <div class="pure-control-group">
          <label>&nbsp;</label>
          <button class="pure-button pure-input-1-2 pure-button-primary" onclick="submit_page();">Save</button>
        </div>
        
        <div class="pure-control-group expg">
          <label>&nbsp;</label>
          <button class="pure-button" onclick="delete_page();">Delete</button>
          <button class="pure-button" onclick="__data = []; __instances = []; set_data();">New Page</button>
        </div>
      </div>
      
      <div class="expg pure-form pure-form-aligned ui-widget-content ui-corner-all" style="padding: 10px; margin-top: 5px;">
        <legend>New Plugin</legend>
        
        <div class="pure-control-group">
          <label>Plugin</label>
          <select id="plugin"></select>
        </div>
  
        <div class="pure-control-group">
          <label>Name</label>
          <input id="inst_name" type="text" class="pure-input-1-2" placeholder="{e.g. Main Gallery}"></input>
        </div>
        
        <div class="pure-control-group">
          <label>Width</label>
          <input id="inst_width" type="text" class="pure-input-1-2"></input>
        </div>
        
        <div class="pure-control-group">
          <label>Height</label>
          <input id="inst_height" type="text" class="pure-input-1-2"></input>
        </div>
    
        <div class="pure-control-group">
          <label>&nbsp;</label>
          <button class="pure-button" onclick="add_instance();">Add to Page</button>
        </div>
      </div>
      
      <div id="inst_view" >
        <div class="expg pure-form pure-form-aligned ui-widget-content ui-corner-all" style="padding: 10px; margin-top: 5px;">
          <table class="pure-table pure_table_extra" style="width: 100%;" cellPadding=0 cellSpacing=0>
            <thead>
              <tr>
                <th>Plugins (added)</th>
                <th width="50px">&nbsp;</th>
                <th width="50px"></th>
              </tr>
            </thead>
            <tbody id="inst_body"></tbody>
          </table>
        </div>
      </div>
      
      <div class="expg pure-form pure-form-stacked  ui-widget-content ui-corner-all" style="padding: 10px; margin-top: 5px;">
        <legend>All Pages</legend>
        <div id="pages" style="padding: 10px;"></div>
      </div>
    </td>
  <tr>
</table>

<div id="dialog_inst" class="pure-skin-mine_tp" style="display: none;" title="Edit Plugin">
  <div class="pure-form pure-form-aligned" style="padding: 10px;">
    <div class="pure-control-group">
      <label>Plugin</label>
      <select id="plugin_ed"></select>
    </div>
  
    <div class="pure-control-group">
      <label>Name</label>
      <input id="inst_name_ed" type="text" class="pure-input-1-2" placeholder="{e.g. Main Gallery}"></input>
    </div>
    
    <div class="pure-control-group">
      <label>Width</label>
      <input id="inst_width_ed" type="text" class="pure-input-1-2"></input>
    </div>
    
    <div class="pure-control-group">
      <label>Height</label>
      <input id="inst_height_ed" type="text" class="pure-input-1-2"></input>
    </div>
  </div>
</div>

<div id="dialog_change" class="pure-form pure-form-aligned"  title="Change Name" style="display: none;">
  <span title="" onclick="change_icon('');" class="fa fa-fw fa-lg af">&nbsp;</span>
  <?php $count = 0;for($i = 0, $il = hexdec(197); $i < $il; $i++) { ?>
    <?php 
      if (sprintf('%03x', $i) == '00f' ||
          sprintf('%03x', $i) == '01f' ||
          sprintf('%03x', $i) == '03f' ||
          sprintf('%03x', $i) == '04f' ||
          sprintf('%03x', $i) == '05f' ||
          sprintf('%03x', $i) == '06f' ||
          sprintf('%03x', $i) == '07f' ||
          sprintf('%03x', $i) == '08f' ||
          sprintf('%03x', $i) == '09f' ||
          sprintf('%03x', $i) == '0af' ||
          sprintf('%03x', $i) == '0cf' ||
          sprintf('%03x', $i) == '0df' ||
          sprintf('%03x', $i) == '0ef' ||
          sprintf('%03x', $i) == '0ff' ||
          sprintf('%03x', $i) == '10f' ||
          sprintf('%03x', $i) == '11f' ||
          sprintf('%03x', $i) == '12f' ||
          sprintf('%03x', $i) == '13f' ||
          sprintf('%03x', $i) == '14f' ||
          sprintf('%03x', $i) == '15f' ||
          sprintf('%03x', $i) == '16f' ||
          sprintf('%03x', $i) == '17f' ||
          sprintf('%03x', $i) == '18f' ||
          sprintf('%03x', $i) == '116' ||
          sprintf('%03x', $i) == '117' ||
          sprintf('%03x', $i) == '020' ||
          sprintf('%03x', $i) == '0b3' ||
          sprintf('%03x', $i) == '0b4' ||
          sprintf('%03x', $i) == '0b5' ||
          sprintf('%03x', $i) == '0b6' ||
          sprintf('%03x', $i) == '0b7' ||
          sprintf('%03x', $i) == '0b8' ||
          sprintf('%03x', $i) == '0b9' ||
          sprintf('%03x', $i) == '0ba' ||
          sprintf('%03x', $i) == '0bb' ||
          sprintf('%03x', $i) == '0bc' ||
          sprintf('%03x', $i) == '0bd' ||
          sprintf('%03x', $i) == '0be' ||
          sprintf('%03x', $i) == '0bf') 
        continue;
    ?>
    <span title="&#xf<?php echo sprintf('%03x', $i); ?>;" onclick="change_icon('&#xf<?php echo sprintf('%03x', $i); ?>;');" class="fa fa-fw fa-lg af">&#xf<?php echo sprintf('%03x', $i); ?>;</span>
  <?php }?>
</div>

<script type="text/javascript" src="src/<?php echo $dir; ?>/jstree/_lib/jquery.cookie.js"></script>
<script type="text/javascript" src="src/<?php echo $dir; ?>/jstree/_lib/jquery.hotkeys.js"></script>
<script type="text/javascript" src="src/<?php echo $dir; ?>/jstree/jquery.jstree.js"></script>
<script type="text/javascript" src="../3rd_party/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
  var __plugins = JSON.parse('<?php echo addslashes(json_encode($plugins)); ?>');
  var __instances = JSON.parse('<?php echo addslashes(json_encode($instances)); ?>');
  var __data = JSON.parse('<?php echo addslashes(json_encode($data)); ?>');
  var __pages = JSON.parse('<?php echo addslashes(json_encode($pages)); ?>');
  var __root = Utils.get_root(__pages);
  var __install_url = '<?php echo URL . INSTALL_DIR; ?>';
  var __home_url = '<?php echo URL . HOME_DIR; ?>';
  var __dir = '<?php echo $dir; ?>';
  var __file = '<?php echo $file; ?>';
  var __system_id = '<?php echo $system_id; ?>';
  
  $(function(){
    $('.play').button({
      text: false,
      icons: {
        primary: 'ui-icon-carat-1-e'
      }
    });
    $('#nav1').button();
    $('#nav2').button();
    $('#nav3').button();
    $('#nav4').button();
    
    tinyMCE.init( {
      // General options
      mode: 'exact',
      elements: 'html',
      theme: 'advanced',

      plugins: 'pdw,filebrowser,autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist',
      // Theme options
      theme_advanced_buttons1: 'pdw_toggle,|,undo,redo,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,fontselect,fontsizeselect,|,forecolor,backcolor,|,image,media,|,code,preview,|,fullscreen',
      theme_advanced_buttons2: 'search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,cleanup,help,|,insertdate,inserttime',
      theme_advanced_buttons3: 'tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,advhr,|,print,|,ltr,rtl',
      theme_advanced_buttons4: 'insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak',
      theme_advanced_toolbar_location: 'top',
      theme_advanced_toolbar_align: 'left',
      theme_advanced_statusbar_location: 'bottom',
      theme_advanced_resizing: true,

      file_browser_callback: 'filebrowser',
      pdw_toggle_on: '1',
      pdw_toggle_toolbars: '2,3,4',

      theme_advanced_resizing: true,
      theme_advanced_resize_horizontal: false,
      
      // Example content CSS (should be your site CSS)
      theme_advanced_font_sizes: '10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px,25px,26px,27px,28px,29px,30px',
    });

    set_plugin_new();
    set_data();
    set_pages();
  });

  function set_pages() {
    $("#pages").empty();
    $('#pages').append('<ul id="pgul_' + __root.id + '"></ul>');
    __set_pages(__root, $('#pgul_' + __root.id));
    $("#pages")
    .jstree({ "plugins" : ["themes", "html_data", "ui"] })
    .on('loaded.jstree', function() {
      $("#pages").jstree('open_all');
    })
    .bind("select_node.jstree", function (event, data) { 
      var req = {
        id: data.rslt.obj.attr("value")
      };
      Ajax.request(
        'firewall.php?d=' + __dir + '&f=' + __file + '&m=change_page',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          __data = [ rslt.page ];
          __instances = rslt.instances;
          set_data();
        },
        null
      );
    })
    .delegate("a", "click", function (event, data) { event.preventDefault(); });
  }

  function __set_pages(node, elm) {
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      elm.append('<li value="' + itm.id +'">' +
                    '<a href="#"' + ((__data.length > 0 && __data[0].id == itm.id) ? ' class="jstree-clicked"' : '') + '>' + itm.name + '</a>' +
                    ((itm.__c.length > 0) ? '<ul id="pgul_' + itm.id + '"></ul>' : '') + 
                 '</li>');
      if (itm.__c.length > 0) {
        __set_pages(itm, $('#pgul_' + itm.id));
      }
    }
  }

  function set_plugin_new() {
    $('#plugin').empty();
    $('#inst_name').val(__plugins[0].folder);
    $('#inst_width').val('100%');
    $('#inst_height').val('100%');
    for (var idx in __plugins) {
      var itm = __plugins[idx];
      $('#plugin').append('<option value="' + itm.id + '">' + itm.folder +'</option>');
    }
    $('#plugin')[0].onchange = function() {
      $('#inst_name').val($("#plugin option:selected").text());
    };
  }

  function set_data() {
    $('#tb_page').empty();
    
    $('#uploader').empty();
    $('#uploader').append('<span id="spanButtonPlaceHolder"></span>');
    $('#icon').empty();
    
    $('#parent').empty();
    set_parent(__root, '', true);
    
    if (__data.length > 0) {
      $('#tb_page').append('<span class="ui-button-text">' + __data[0].name + '</span>');
      set_instances();
      
      Url.insert_param('pg', __data[0].id);
      $('.expg').show();

      $('#name').val(__data[0].name);
      $('#icon').html(__data[0].icon);
      $('#parent').val(__data[0].parent_id);
      $('#is_default')[0].checked = (__data[0].is_default == 1) ? true : false;
      $('#is_visible')[0].checked = (__data[0].is_visible == 1) ? true : false;
      if (tinyMCE.get('html')) {
        tinyMCE.get('html').setContent(__data[0].html);
      } else {
        $('#html').val(__data[0].html);
      }
      $('#js').val(__data[0].js);
      $('#css').val(__data[0].css);
      
    } else {
      $('#tb_page').append('<span class="ui-button-text">New Page</span>');
      Url.insert_param('pg', 0);
      $('.expg').hide();

      $('#name').val('');
      $('#parent').val(0);
      $('#is_default')[0].checked = (__pages.length  == 0) ? true : false;
      $('#is_visible')[0].checked = true;
      if (tinyMCE.get('html')) {
        tinyMCE.get('html').setContent('');
      } else {
        $('#html').val('');
      }
      $('#js').val('');
      $('#css').val('');
    }

    $('#is_default')[0].disabled = $('#is_default')[0].checked;
  }
  
  function set_parent(node, prefix, selectable) {
    selectable = (selectable && (__data.length == 0 || __data[0].id != node.id));
    $('#parent').append('<option value="' + node.id + '" ' + ((selectable) ? '' : 'disabled="disabled"') + '>' + ((prefix == '') ? '' : prefix + ') ') + node.name +'</option>');
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      set_parent(itm, ((prefix == '') ? '(' : '\u2002' + prefix + '-') + (parseInt(idx, 10) + 1), selectable);
    }
  }

  function set_instances() {
    $('#inst_body').empty();
    for (var idx in __instances) {
      var itm = __instances[idx];
      itm.__added = 0
      if (__data[0].html.indexOf(Utils.get_inst_cd(itm)) != -1) {
        itm.__added = 1;
      }
      $('#inst_body').append(
          '<tr class="' + ((idx % 2 == 0) ? 'pure-table-even' : 'pure-table-odd') + '">' + 
            '<td>' + ((itm.__added && itm.__added == 1) ? itm.name : '<a class="rdlnk" href="#" onclick="insert_code(' + itm.id + ');">' + itm.name + '</a>') + '</td>' +
            '<td>' + itm.__folder + '</td>' +
            '<td>' + 
              '<img src="src/' + __dir + '/images/edit.png" onclick="edit_instance(' + itm.id + ', event);"></img>' + 
              '<img src="src/' + __dir + '/images/delete.png" onclick="delete_instance(' + itm.id + ');"></img>' + 
            '</td>' + 
          '</tr>');
    }
    if (__instances.length == 0) {
      $('#inst_view').hide();
    } else {
      $('#inst_view').show();
    }
  }

  function submit_page() {
    if (__data.length > 0) {
      req = __data[0]
    } else {
      req = {
        icon: ''
      };
    }
    req.name = $('#name')[0].value;
    req.sys_id = __system_id;
    req.parent_id = $("#parent option:selected").val();
    req.is_default = $('#is_default')[0].checked ? 1 : 0;
    req.is_visible = $('#is_visible')[0].checked ? 1 : 0;
    req.html = tinyMCE.get('html').getContent();
    req.js = $('#js')[0].value;
    req.css = $('#css')[0].value;

    Ajax.request(
      'firewall.php?d=' + __dir + '&f=' + __file + '&m=submit_page',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        if (__data.length == 0) {
          __instances = [];
          __pages.push(rslt);
        } else {
          for (var idx in __pages) {
            var itm = __pages[idx];
            if (itm.id == rslt.id) {
              __pages[idx] = rslt;
            }
          }
        }
        __root = Utils.get_root(__pages);
        __data = [ rslt ];
        set_data();
        set_pages();
      },
      null
    );
  }

  function delete_page() {
    Ajax.request(
      'firewall.php?d=' + __dir + '&f=index_system&m=delete_page',
      'req=' + Utils.encodeURI(JSON.stringify(__data[0])),
      function(rslt) {
        $.blockUI();
        if (rslt.length > 0) {
          location.href = __install_url + '?d=' + __dir + '&f=index_page&sys=' + __system_id + '&pg=' + rslt[0].id;
        } else {
          location.href = __install_url + '?d=' + __dir + '&f=index_system&sys=' + __system_id + '&active=1';
        }
      },
      { confirm: 1 }
    );
  }

  function add_instance() {
    var req = {
      page_id: __data[0].id,
      plugin_id: $("#plugin option:selected").val(),
      sys_id: __system_id,
      name: $('#inst_name')[0].value,
      width: $('#inst_width')[0].value,
      height: $('#inst_height')[0].value,
      __folder: $("#plugin option:selected").text()
    };
    
    Ajax.request(
      'firewall.php?d=' + __dir + '&f=' + __file + '&m=submit_instance',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __instances.push(rslt);
        Utils.sort_by_attr('name', __instances);
        __data[0].html = '<p>' + Utils.get_inst_cd(rslt) + '</p>' + __data[0].html;
        set_data();
        set_plugin_new();
      },
      null
    );
  }

  function delete_instance(id) {
    var req = Utils.get_by_id(id, __instances);
    if (req) {
      Ajax.request(
        'firewall.php?d=' + __dir + '&f=' + __file + '&m=delete_instance',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          __data[0].html = __data[0].html.replace('<p>' + Utils.get_inst_cd(rslt) + '</p>', '');
          __data[0].html = __data[0].html.replace(Utils.get_inst_cd(rslt), '');
          Utils.splice_by_id(id, __instances);
          set_data();
        },
        { confirm: 1 }
      );
    }
  }

  function insert_code(id) {
    var req = Utils.get_by_id(id, __instances);
    if (req) {
      __data[0].html = '<p>' + Utils.get_inst_cd(req) + '</p>' + __data[0].html;
      Ajax.request(
        'firewall.php?d=' + __dir + '&f=' + __file + '&m=submit_page',
        'req=' + Utils.encodeURI(JSON.stringify(__data[0])),
        function(rslt) {
          set_data();
          set_instances();
        },
        null
      );
    }
  }

  function edit_instance(id, ev) {
    $('#plugin_ed').empty();
    for (var idx in __plugins) {
      var itm = __plugins[idx];
      $('#plugin_ed').append('<option value="' + itm.id + '">' + itm.folder +'</option>');
    }

    var req = Utils.get_by_id(id, __instances);
    var old_cd = Utils.get_inst_cd(req);
    if (req) {
      $('#plugin_ed').val(req.plugin_id);
      $('#inst_name_ed').val(req.name);
      $('#inst_width_ed').val(req.width);
      $('#inst_height_ed').val(req.height);

      $('#dialog_inst').dialog({
        position: {
          my: 'left-300 bottom+20',
          of: ev.target
        },
        buttons: {
          'OK': function() {
            req.plugin_id = $("#plugin_ed option:selected").val();
            req.name = $('#inst_name_ed')[0].value;
            req.width = $('#inst_width_ed')[0].value;
            req.height = $('#inst_height_ed')[0].value;
            req.__folder = $("#plugin_ed option:selected").text();

            Ajax.request(
              'firewall.php?d=' + __dir + '&f=' + __file + '&m=submit_instance',
              'req=' + Utils.encodeURI(JSON.stringify(req)),
              function(rslt) {
                Utils.sort_by_attr('name', __instances);
                set_instances();

                __data[0].html = __data[0].html.replace(old_cd, Utils.get_inst_cd(rslt));
                set_data();
              },
              null
            );
            $(this).dialog('close');
          },
          'Cancel': function() { 
            $(this).dialog('close');
          }
        }
      });
    }
  };

  function change_icon(val) {
    __data[0].icon = val;
    set_data();
    $('#dialog_change').dialog('close');
  };

  function select_icon(ev) {
    $('#dialog_change').dialog({
      width: 750,
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
    });
  };
</script>